//
//  XCComposeController.swift
//  XCMicroBo
//
//  Created by 1 on 16/3/16.
//  Copyright © 2016年 1. All rights reserved.
//

import UIKit
import SnapKit
import AFNetworking

class XCComposeController: UIViewController {
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        setupUI()
        

        registNotification()

    }
    
    func close(){
        dismissViewControllerAnimated(true, completion: nil)
    }
    func send(){
        print("发布微博")
        
        //发送数据
        sendMessage()
    }
    
    
    
    
    //懒加载子控件
    //textView
    //    let myTextView : UITextView = UITextView()
    lazy var myTextView : UITextView = {
        
        let textView = UITextView()
        textView.backgroundColor = UIColor.yellowColor()
        //设置代理
        textView.delegate = self
        
        //设置键盘的收起方式
        textView.keyboardDismissMode = .OnDrag
        
        //设置键盘竖直滚动
        textView.alwaysBounceVertical = true
        
        return textView
    }()
    
    //占位标签
    lazy var placeholdLabel : UILabel = UILabel.labelWith("喝啤酒就喝冰镇的！冰镇啤酒", textColor: UIColor.darkGrayColor(), textFont: 14)
    
    //懒加载toolBar
    lazy var myToolBar : UIToolbar = UIToolbar()
    
    
    //如果在这里添加约束的话  会报错  不知道为什么
//    //navigation.titleView
//    lazy var myTitleView : UIView = {
//        
//        let tv = UIView()
//        
//        let titleLabel : UILabel = UILabel.labelWith("发布微博", textColor: UIColor.blackColor(), textFont: 16)
//        tv.addSubview(titleLabel)
//        
//        let nameLabel = UILabel.labelWith(UserCount.shareAcount.name ?? "", textColor: UIColor.darkGrayColor(), textFont: 13)
//        tv.addSubview(nameLabel)
    
//        titleLabel.snp_makeConstraints(closure: { (make) -> Void in
//            
//            make.top.left.right.equalTo(tv)
//        })
//        
//        nameLabel.snp_makeConstraints(closure: { (make) -> Void in
//            
//            make.bottom.left.right.equalto(tv)
//        })
    
        
//        return tv
//    }()
    
    
    //发布微博的方法
    func sendMessage(){
        
        let urlString = "https://api.weibo.com/2/statuses/update.json"
        
        let manager = AFHTTPSessionManager()
        
        if let token = UserCount.shareAcount.access_token {
        
            let parameters = ["access_token" : token , "status" : myTextView.text]
            
            
            
            manager.POST(urlString, parameters: parameters, progress: nil, success: { (_, result) -> Void in
                
                print(result)
                
                }, failure: { (_, error) -> Void in
                    
                    print(error)
            })
        }
        
        
    }
    
    
    //选择图片的方法
    func selectPicture(){
        
        print("选择图片\(__FUNCTION__)")
    }
    
    //选择表情的方法
    func selectEmoticon (){
    
        print("选择表情\(__FUNCTION__)")
        
    }
    
    
    //监听键盘变化通知
    func registNotification () {
        
        //监听键盘的变化
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardChange", name: UIKeyboardDidChangeFrameNotification, object: nil)
    }
    
 
    //移除通知
    deinit{
        
        NSNotificationCenter.defaultCenter().removeObserver(self)
    }
}

//设置UI
extension XCComposeController {

    
    func setupUI(){
        
        view.backgroundColor = UIColor.whiteColor()
        
        setTextView()
        
        setNavigation()
        
        setMyToolBar()
        
    }
    
    func setTextView (){
    
        self.view.addSubview(myTextView)
        myTextView.addSubview(placeholdLabel)
        
        
        
        myTextView.snp_makeConstraints { (make) -> Void in
            
            make.top.left.right.equalTo(self.view)
            make.height.equalTo(screenHight / 3)
        }
        
        placeholdLabel.snp_makeConstraints { (make) -> Void in
            
            make.top.equalTo(myTextView.snp_top).offset(8)
            make.left.equalTo(myTextView.snp_left).offset(6)
        }

    }
    
    
    
    //设置navigation
    func setNavigation() {
        
        
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "关闭", style: .Plain, target: self, action: "close")
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "发布", style: .Plain, target: self, action: "send")
        //设置发布按钮不可与用户交互
        navigationItem.rightBarButtonItem?.enabled = false
        
        
        let myTitleView = UIView(frame: CGRect(x: 0, y: 0, width: 200, height: 44))
        
        navigationItem.titleView = myTitleView
        
        
        let titleLabel : UILabel = UILabel.labelWith("发布微博", textColor: UIColor.blackColor(), textFont: 16)
        myTitleView.addSubview(titleLabel)
        
        let nameLabel = UILabel.labelWith(UserCount.shareAcount.name ?? "", textColor: UIColor.darkGrayColor(), textFont: 13)
        myTitleView.addSubview(nameLabel)
        
        
        
        
        titleLabel.snp_makeConstraints { (make) -> Void in
            
            make.top.equalTo(myTitleView.snp_top)
            make.centerX.equalTo(myTitleView.snp_centerX)
        }
        
        nameLabel.snp_makeConstraints { (make) -> Void in
            
            make.bottom.equalTo(myTitleView.snp_bottom)
            make.centerX.equalTo(myTitleView.snp_centerX)
        }
        
        
    }
    
    
    
    func setMyToolBar(){
        
        view.addSubview(myToolBar)
        
        var items = [UIBarButtonItem]()
        
        //添加 UIBarButtonItem类型的对象到数据源数组中
        let itemSettings = [["imageName": "compose_toolbar_picture","actionName": "selectPicture"],
            ["imageName": "compose_mentionbutton_background"],
            ["imageName": "compose_trendbutton_background"],
            ["imageName": "compose_emoticonbutton_background", "actionName": "selectEmoticon"],
            ["imageName": "compose_add_background"]]


        for item in itemSettings{
            
            let imageName = item["imageName"]
        
            let btn = UIButton.buttonWithImage(imageName, backImage: nil)
            
            if let action = item["actionName"] {
                
                btn.addTarget(self, action: Selector(action), forControlEvents: .TouchUpInside)
            }
            
            //将button转化为 barkButton
            let barButton = UIBarButtonItem(customView: btn)
            
            //加弹簧  用来布局视图
            let barButtonItem = UIBarButtonItem(barButtonSystemItem: .FlexibleSpace, target: nil, action: nil)
            
            items.append(barButton)
            items.append(barButtonItem)
        }
        
        //移除最后一个弹簧
        items.removeLast()
        
        myToolBar.items = items
        
        myToolBar.backgroundColor = UIColor.yellowColor()
        
        myToolBar.snp_makeConstraints { (make) -> Void in
            
            make.left.bottom.right.equalTo(self.view)
            make.height.equalTo(44)
        }
    }


}

//监听textView
extension XCComposeController : UITextViewDelegate {

    func textViewDidChange(textView: UITextView) {
        
        placeholdLabel.hidden = myTextView.hasText()
        
        navigationItem.rightBarButtonItem?.enabled = myTextView.hasText()
    }
    
    
}

